import {deepFullCopy, messages, queryCurrencyPrecision} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { message, Spin , Form, Button, Modal, Alert, Select, AutoComplete, Icon, Affix } from 'antd';
import common  from'containers/financial-management/check-center/check-common'
import 'styles/setting/wait-for-billing/search-new-billing.scss'
import BillingService from 'containers/financial-management/wait-for-billing/wait-for-billing.service'
import menuRoute from "routes/menuRoute";
import constants from "share/constants";
const FormItem = Form.Item;
const Option = Select.Option;
import AddressPicker from 'containers/financial-management/wait-for-billing/new-billing/address-picker';
import ResizeTable from 'components/resize-table'

class SearchNewBilling extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      searchParams: JSON.stringify(this.props.searchBilling) !== "{}" ? this.props.searchBilling : this.props.location.state.params,
      billingType: JSON.stringify(props.billingType) !== "{}" ? props.billingType : props.params.billingType,
      invoiceInfo: {},
      data: [],
      pagination: {
        total: 0,
      },
      tableLoading: false,
      page: 0,
      columns: [
        {title: messages('financial-management.key403')/*序号*/, dataIndex: 'sequence', render: (text, record, index) => this.state.page * 10 + index + 1, width: 80},
        {title: messages('financial-management.key515')/*法人*/, dataIndex: 'expenseLegalEntityName'},
        {title: messages('financial-management.key676')/*费用条数*/, dataIndex: 'counts'},
        {
          title: messages('financial-management.key677')/*费用金额*/,
          dataIndex: 'invoiceAmount',
          render: (value, record) => this.filterMoney(value,queryCurrencyPrecision(record.invoiceCurrency))
        },
        {
          title: messages('financial-management.key678')/*待开票金额*/,
          dataIndex: 'orderAmount',
          render: (value, record) => this.filterMoney(value,queryCurrencyPrecision(record.orderCurrency))
        },
        {title: messages('financial-management.key679')/*明细查询*/, dataIndex: 'viewDetail', render: (value, record) => {
            return <a onClick={() => this.goViewDetail(record)}>{messages('financial-management.key679')/*明细查询*/}</a>
          }},
        {title: messages('financial-management.key514')/*确认开票*/, dataIndex: 'confirm', render: (value, record) => {
            return <a onClick={() => this.confirm(record)}>{messages('financial-management.key514')/*确认开票*/}</a>
          }},
      ],
      showAddressPicker: false,
      showConfirmModal: false,
      okLoading: false,
      ruleTypeOptions: [],
      defaultAddressInfo: {},
      invoiceTitle: [],
      dataSource: [],
      legalEntityOid: '',
      taxpayerNumber: null,
      expenseLETaxPayerNumber: '',
      emailInvoice:''
    };
    this.waitForBillingRouter = menuRoute.getRouteItem('wait-for-billing-list');
  }

  componentWillMount(){
    this.getInvoiceInfo();
    this.getList();
    // this.getInvoiceTitle();
    BillingService.getEmail().then((res)=>{
      if(res.status == 200 && res.data)
      this.setState({emailInvoice:res.data[0].messageKey})
    })
  }

  //查询开票-获取开票费用信息
  getInvoiceInfo = () => {
    const { billingType, searchParams } = this.state;
    this.setState({loading: true});
    BillingService.getInvoiceMessage(billingType, searchParams).then(res =>{
      this.setState({
        invoiceInfo: res.data,
        loading: false
      })
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  getList = () => {
    const { billingType, searchParams, page } = this.state;
    let temp = deepFullCopy(searchParams);
    temp.page = page;
    this.setState({tableLoading: true});
    BillingService.getViewDetail(billingType, temp).then((res) => {
      this.setState({
        data: res.data.rows,
        tableLoading: false,
        pagination: {
          total: Number(res.data.total),
          onChange: this.onChangePager,
          current: page + 1
        },
      });
    }).catch(e => {
      this.setState({tableLoading: false});
      message.error(e.response.data.message);
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  goViewDetail = record => {
    this.context.router.push({
      pathname: `${menuRoute.getRouteItem('search-billing-detail').url.replace(':billingType',this.state.billingType).replace(':legalEntityOid',record.expenseLegalEntityOid)}`,
      state: {params: this.state.searchParams}
    });
  };

  confirm = record => {
    this.setState({
      showConfirmModal: true,
      expenseLETaxPayerNumber: record.expenseLETaxPayerNumber,
      legalEntityOid: record.expenseLegalEntityOid,
      invoiceTitle: [
        {
          "id": record.expenseLegalEntityId || '',
          "invoice_title": record.expenseLegalEntityName || '',
          "tax_registration_number": record.expenseLETaxPayerNumber || ''
        }
      ]
    },() => {
      const { invoiceTitle, expenseLETaxPayerNumber } = this.state;
      let temp = invoiceTitle.find(item => item.tax_registration_number === expenseLETaxPayerNumber) || {}
      this.handleChangeInvoice(temp.invoice_title);
    });
  };

  //获得抬头信息
  getInvoiceTitle = () => {
    let params = {
      companyOid: this.props.company.companyOID
    };
    BillingService.getInvoiceTitle(this.state.billingType, params).then(res => {
      if (res.data) {
        this.setState({invoiceTitle: res.data})
      }else {
        this.setState({invoiceTitle: [
          {
            "id": 16474,
            "invoice_title": "金拱门(中国)有限公司",
            "tax_registration_number": "91310000607295837G"
          }
        ]})
      }

    }).catch(e => {
      message.error(e.response.data.message)
    });
  };

  //获取供应商发票类型
  getVendorInvoiceType = () => {
    const { billingType, taxpayerNumber } = this.state;
    BillingService.getVendorInvoiceType(billingType, taxpayerNumber).then(res => {
      if (res.data && res.data.length > 0) {
        if (res.data.filter(item => !this.switchReceiving(item.type)).length > 0) {
          this.getDefaultAddress();
        }
        this.setState({ ruleTypeOptions: res.data }, () => {
          this.props.form.setFieldsValue({ invoiceApplyType: res.data[0].type });
        });
      }
    }).catch(e => {
      this.setState({ ruleTypeOptions: [] }, () => {
        this.props.form.setFieldsValue({ invoiceApplyType: undefined });
      });
      message.error(e.response.data.message);
    })
  };

  //根据发票类型状态切换收件信息
  switchReceiving = (type) => {
    let email = ['ELECTRONICORDINARY'];
    return (type && ~email.indexOf(type));
  };

  //获得默认地址
  getDefaultAddress = () => {
    BillingService.getDefaultAddress().then(res => {
      this.setState({defaultAddressInfo: res.data})
    })
  };

  //确认开票
  handleOpenTicket = () => {
    let {searchParams, invoiceTitle, defaultAddressInfo, legalEntityOid} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let temp = {};
        if (!this.switchReceiving(values.invoiceApplyType) && (!defaultAddressInfo || !defaultAddressInfo.billingContactOID)) {
          message.warn(messages('financial-management.key460'/*请选择收货地址*/));
          return;
        }
        if (!this.switchReceiving(values.invoiceApplyType)) {
          temp.billingContactOID = defaultAddressInfo.billingContactOID
        }
        temp.qid = invoiceTitle.filter(item => item.invoice_title === values.title)[0].id;
        temp.taxpayerNumber = invoiceTitle.filter(item => item.invoice_title === values.title)[0].tax_registration_number;
        temp.currencySymbol = constants.CurrencyCode[this.props.companyConfiguration.currencyCode];
        if (this.state.billingType !== 'CLOUD_HELIOS_HOTEL' && searchParams.company) {
          temp.vendorAccountId = searchParams.company.vendorAccountId;
          temp.vendorAccountName = searchParams.company.vendorAccountName;
        }
        Object.assign(searchParams, {expenseSearchLegalEntityOIDs: [legalEntityOid]});
        let params = { ...searchParams, ...values, ...temp };
        this.openTicket(params)
      }
    })
  };

  //取消确认开票
  onConfirmCancel = () => {
    this.setState({showConfirmModal: false})
  };

  //开票
  openTicket = (params) => {
    this.setState({okLoading: true});
    BillingService.applyForReceiptedInvoice(this.state.billingType, params).then(res => {
      this.setState({okLoading: false});
      if (res.status === 200) {
        message.success(messages('financial-management.key521'/*申请成功!*/));
        this.onConfirmCancel();
        this.context.router.push(this.waitForBillingRouter.url.replace(':billingType', this.state.billingType))
      }
    }).catch(() => {
      this.setState({okLoading: false});
      message.error(messages('financial-management.key522'/*申请失败!*/))
    })
  };

  //选择更多收件地址
  showAddressPicker = () => {
    this.setState({showAddressPicker: true});
  };

  //取消地址选择
  AddressPickerCancel = () => {
    this.setState({showAddressPicker: false});
  };

  //确认选择地址
  handleChooseAddress = (value) => {
    this.setState({defaultAddressInfo: value})
  };

  //根据发票类型状态切换收件信息
  switchReceiving = (type) => {
    let email = ['ELECTRONICORDINARY'];
    return (type && ~email.indexOf(type));
  };

  emailHandleChange = (value) => {
    this.setState({
      dataSource: !value || value.indexOf('@') >= 0 ? [] : [
        `${value}@${this.props.user.email && ~this.props.user.email.indexOf('@') ? this.props.user.email.split('@')[1] : ''}`,
        `${value}@163.com`,
        `${value}@126.com`,
        `${value}@qq.com`,
        `${value}@sina.com`,
      ],
    });
  };

  goBack = () => {
    this.context.router.push(this.waitForBillingRouter.url.replace(':billingType', this.state.billingType));
  };

  handleChangeInvoice = value => {
    const { invoiceTitle } = this.state;
    let temp = invoiceTitle.find(item => item.invoice_title === value) || {};
    this.setState({ taxpayerNumber: temp.tax_registration_number },() => {
      this.getVendorInvoiceType();
    });
  };

  render(){
    const { invoiceInfo, loading, data, pagination, tableLoading, columns,  showConfirmModal, ruleTypeOptions,
      defaultAddressInfo, showAddressPicker, invoiceTitle, dataSource, okLoading, taxpayerNumber,
      expenseLETaxPayerNumber } = this.state;
    const {fullName, phone, country, stateProvince, cityRegion, streetLine, billingContactOID} = defaultAddressInfo;
    const {getFieldDecorator} = this.props.form;
    const {user} = this.props;
    let invoiceApplyType = this.props.form.getFieldValue('invoiceApplyType');
    let initValue = invoiceTitle.find(item => item.tax_registration_number === expenseLETaxPayerNumber) || {};
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 14},
    };
    const html = {
      __html: messages('financial-management.key554',{arg1:invoiceInfo.total ? invoiceInfo.total.counts : 0}/*共计 <span class='invoice-counts-num'>{arg1}</span> 条费用，*/)
    };
    return (
      <div className='search-new-billing'>
        <Spin spinning={loading}>
          <div className='result-title'>{messages('financial-management.key519'/*查询结果*/)}：</div>
          {invoiceInfo.total &&
          <div className='invoice-counts'>
            <span dangerouslySetInnerHTML={html} />
            {messages('financial-management.key520'/*总共金额*/)}&nbsp;
            <span  className='invoice-counts-num'>{invoiceInfo.total.invoiceCurrency}{common.formatCurrency(invoiceInfo.total.invoiceAmount)}</span>
            <span  className='invoice-counts-base'>{invoiceInfo.total.baseCurrency}{common.formatCurrency(invoiceInfo.total.baseCurrencyAmount)}</span>
          </div>
          }
        </Spin>
        <div style={{margin: '10px 0px 20px', borderBottom: '1px solid #cfcfcf'}}/>
        <ResizeTable
          dataSource={data}
          bordered
          columns={columns}
          rowKey={'expenseLegalEntityOid'}
          loading={tableLoading}
          pagination={pagination}
        />
        <Modal visible={showConfirmModal}
               width={800}
               title={messages('financial-management.key514'/*确认开票*/)}
               wrapClassName="search-new-billing"
               className='confirm-receipt-modal'
               onCancel={() => this.setState({showConfirmModal: false})}
               footer={[
                 <Button key="back" onClick={this.onConfirmCancel}>{messages('common.cancel'/*取消*/)}</Button>,
                 <Button key="submit" type="primary" loading={okLoading}
                         onClick={this.handleOpenTicket}>{messages('common.ok'/*确定*/)}</Button>
               ]}>
          <Form>
            <Alert message={messages('financial-management.key645')/*注意！开票抬头如果不是共用一个收件地址或邮箱，请单独进行开票！*/} type="info" showIcon style={{marginBottom: 20}}/>
            <FormItem  {...formItemLayout} label={messages('financial-management.key428'/*开票抬头*/)}>
              {getFieldDecorator("title", {
                rules: [{
                  required: true,
                  message: messages('financial-management.key471'/*请选择发票抬头*/)
                }],
                initialValue: initValue.invoice_title
              })(
                <Select
                  placeholder={messages('financial-management.key472'/*请选择抬头*/)}
                  onChange={this.handleChangeInvoice}
                >
                  {invoiceTitle.map(item => <Option key={item.invoice_title}>{item.invoice_title}</Option>)}
                </Select>
              )}
            </FormItem>
            {
              taxpayerNumber && (
                <FormItem {...formItemLayout} label={messages('financial-management.key433'/*开票类型*/)}>
                  {getFieldDecorator("invoiceApplyType", {
                    rules: [{
                      required: true
                    }]
                  })(
                    <Select>
                      {ruleTypeOptions.map(item => <Option value={item.type} key={item.type}>{item.name}</Option>)}
                    </Select>
                  )}
                </FormItem>
              )
            }
            {this.switchReceiving(invoiceApplyType) ? (
              <FormItem  {...formItemLayout} label={messages('financial-management.key473'/*收件邮箱*/)}>
                {getFieldDecorator("email", {
                  rules: [{
                    required: true,
                    type: 'email',
                    message: `${messages('common.please.enter')}${messages('financial-management.key474'/*正确的收件邮箱*/)}`
                  }],
                  initialValue: this.state.emailInvoice
                })(
                  <AutoComplete
                    dataSource={dataSource}
                    style={{width: 310}}
                    onChange={this.emailHandleChange}
                    placeholder={messages('common.please.enter')}
                  />
                )}
              </FormItem>
            ) : (
              <FormItem  {...formItemLayout} label={messages('financial-management.key475'/*收件信息*/)}>
                {getFieldDecorator("address", {
                  rules: [{
                    required: true
                  }],
                  initialValue: `${fullName}  ${phone}  ${country}${stateProvince}${cityRegion}${streetLine}`
                })(
                  <div className='receive-info-content'>
                    {fullName}&nbsp;&nbsp;{phone}&nbsp;&nbsp;{country}{stateProvince}{cityRegion}{streetLine}
                    {defaultAddressInfo && defaultAddressInfo.isDefault &&
                    <div className='default-button'>{messages('financial-management.key476'/*默认地址*/)}</div>}
                    <div className='more-address'
                         onClick={this.showAddressPicker}>{messages('financial-management.key477'/*更多地址*/)}<Icon
                      type="down-circle-o" style={{marginLeft: "5px"}}/></div>
                  </div>
                )}
              </FormItem>
            )}
          </Form>
          {showAddressPicker && <AddressPicker visible={showAddressPicker} onCancel={this.AddressPickerCancel}
                                              moreAdress={value => this.handleChooseAddress(value)} flag={'edit'}
                                              billingContactOID={billingContactOID}/>}
        </Modal>
        <Affix offsetBottom={0} className="bottom-bar">
          <Button className="back-btn" onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>
        </Affix>
      </div>
    )
  }
}

SearchNewBilling.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    companyConfiguration: state.login.companyConfiguration,
    searchBilling: state.billing.searchBilling,
    billingType: state.billing.billingType
  }
}

const WrappedSearchNewBilling = Form.create()(SearchNewBilling);
export default connect(mapStateToProps)(WrappedSearchNewBilling);
